package com.tx.admin.modules.generator.runner;

import com.tx.admin.core.controller.SuperController;
import com.tx.admin.modules.generator.entity.ColumnEntity;
import com.tx.admin.modules.generator.entity.TableEntity;
import com.tx.admin.modules.generator.service.ColumnService;
import com.tx.admin.modules.generator.service.TableService;
import com.tx.admin.util.common.ReflectionUtils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class GeneratorRunner implements CommandLineRunner{

    @Autowired
    private List<SuperController> controllerList;

    @Autowired
    private TableService tableService;

    @Autowired
    private ColumnService columnService;

    private void initTable(Class entityClazz){
        ApiModel apiModel = AnnotationUtils.findAnnotation(entityClazz,ApiModel.class);
        TableEntity tableEntity =  new TableEntity();

        tableEntity.setId(apiModel.value());
        tableEntity.setLabel(apiModel.value());
        tableEntity.setEntityClass(entityClazz.getSimpleName());

        List<ColumnEntity> columns = ReflectionUtils.getAllDeclaredFields(entityClazz).stream().map(field -> {
            ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
            ColumnEntity columnEntity = new ColumnEntity();
            columnEntity.setId(tableEntity.getId()+apiModelProperty.value());
            columnEntity.setTableId(tableEntity.getId());
            columnEntity.setFieldType(field.getType().getSimpleName());
            columnEntity.setFieldName(field.getName());
            columnEntity.setLabel(apiModelProperty.value());
            return columnEntity;
        }).collect(Collectors.toList());

        this.tableService.save(tableEntity);
        this.columnService.save(columns);
    }

    @Override
    public void run(String... args) throws Exception {
        if(this.tableService.count() == 0){
            this.controllerList.forEach(val -> {
                this.initTable(val.getEntityClass());
            });
        }
    }
}
